<template>
  <div class="mainBox">
      <div class="container">
        <el-row :gutter="20">
          <el-col :span="12">
            <span>用户组:</span>
            <el-select v-model="searchParam.group_id" clearable filterable placeholder="请选择">
              <el-option
                v-for="item in userGroupsArr"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <span>状态:</span>
            <el-select v-model="searchParam.status" clearable placeholder="请选择">
              <el-option
                v-for="item in statusArr"
                :key="item.value"
                :label="item.text"
                :value="item.value">
              </el-option>
            </el-select>
            <el-button type="primary" @click="getUsersList" size="small" icon="el-icon-search">查询</el-button>
          </el-col>
          <el-col :span="6" >
            <el-button  type="primary" @click="dialogFormVisible = true" size="small" icon="el-icon-plus">添加用户</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table
        :data="userTableData"
        border
        style="width: 100%">
        <el-table-column
          prop="id"
          label="ID"
          width="180"
          align="center">
        </el-table-column>
        <el-table-column
          prop="create_at"
          label="创建时间"
          width="180"
          align="center">
        </el-table-column>
        <el-table-column
          label="名称"
          align="center"
          >
            <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <h2>拥有组：</h2>
              <p v-for="(item, index) in scope.row.groups">{{index+1}}：{{ item.name }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.username }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          prop="role.name"
          label="角色"
          width="180"
          align="center">
        </el-table-column>
        <el-table-column
          prop="update_at"
          label="更新时间"
          align="center">
        </el-table-column>
        <el-table-column
          label="状态"
          width="120"
          align="center"
          >
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status == '1' ? 'success' : 'danger'"
                close-transition>{{scope.row.status | statusFilter}}</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              :type="scope.row.status === 1 ? '':'success'"
              @click="statusHandleEdit(scope.$index, scope.row)">{{scope.row.status === 1 ? '禁用' : '启用'}}</el-button>
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

          <!-- 分页 -->
          <el-pagination
            class="pagination-container" style="margin-top: 20px;"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10,20,50,100]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>

          <!-- dialog 添加用户-->
          <el-dialog title="用户" :visible.sync="dialogFormVisible" @close="closeDialog">
            <el-form :model="form" :rules="rules" ref="addUserForm" label-width="120px" style="">
              <el-form-item label="用户名称" prop="username">
                <el-input v-model="form.username" placeholder="请输入用户名称" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" placeholder="请输入密码" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="用户组" prop="group_id_list">
                <el-select v-model="form.group_id_list" clearable filterable multiple placeholder="请选择">
                  <el-option
                    v-for="item in userGroupsArr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="角色"  prop="role_id">
                <el-select v-model="form.role_id" clearable filterable placeholder="请选择">
                  <el-option
                    v-for="item in rolesArr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="状态">
                <el-switch
                  v-model="status_Boolean"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="add_switchChange"
                  >
                  </el-switch>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('addUserForm')">保存</el-button>
                <el-button @click="resetForm('addUserForm')">重置</el-button>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <!--<el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>-->
            </div>
          </el-dialog>
  </div>
</template>


<script>
import {getUserGroup} from '@/api/userGroup'
import {getUsers,addUser,delUser,getRoles,UserDetail,updateUser} from '@/api/users'
export default{
  data() {
    return {
      total:0,
      pageSize: 10,
      currentPage: 1,
      dialogFormVisible: false,
      form:{
        username: '',
        password:'',
        group_id_list: [],
        role_id: '',
        status: 1
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' }
        ],
        group_id_list: [
          { required: true, message: '请选择用户组', trigger: 'blur' }
        ],
        role_id: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ]
      },
      operType: 1, // 1 add; 2 update
      userId:'',
      status: '1',
      status_Boolean: true,
      searchParam:{
        status: '',
        group_id: '',
        per_page: 10,
        page: 1
      },
      statusArr:[
        {text:'启用',value:1},
        {text:'禁用',value:0}
      ],
      userGroupsArr:[],
      userTableData:[], //用户列表数据
      rolesArr:[] //角色下拉框
    }
  },
  created(){
    this.getUsersList();
    this.getUserGroupList();
    this.getRolesList();
  },
  methods: {
    //获取用户组下拉框列表
    getUserGroupList(){
      getUserGroup({
        per_page: 1000
      },response=> {
        const res = response.data
        if(res.code == 1){
          this.userGroupsArr = (res.data).items
        }
      })
    },
    //用户列表
    getUsersList(){
      getUsers(this.searchParam, response=> {
        const res = response.data
        if(res.code == 1){
          this.userTableData = (res.data).items
          this.total = (res.data).total
        }
      })
     },
    //保存
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
            // console.log('--->>'+ JSON.stringify(this.form))
          if(this.operType == 1){
            this.addUserFun()
          }else{
            this.updateUserFun()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //添加用户
    addUserFun(){
      addUser(this.form, response=> {
        const res = response.data;
        if(res.code == 1){
          this.$message.success('添加成功')
          this.dialogFormVisible = false
          this.getUsersList();
        }
      })
    },
    //更新
    updateUserFun(){
      updateUser(this.userId, this.form, response=> {
        const res = response.data;
        if(res.code === 1){
          this.$message.success('更新成功')
          this.getUsersList();
          this.dialogFormVisible = false
        }
      })
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //详情
    handleEdit(index, row) {
      // console.log(index, row);
      this.userId = row.id
      this.operType = 2
      UserDetail(row.id, response=> {
        const res = response.data;
        if(res.code === 1){
          this.form.username = (res.data).username;
          this.form.password = (res.data).password;
          this.form.group_id_list = [];
          ((res.data).groups).forEach(item=>{
            (this.form.group_id_list).push(item.id)
          })
          this.form.role_id = ((res.data).role).id;
          this.status_Boolean = (res.data.status === 1) ? true : false
          this.dialogFormVisible = true
        }
      })
    },
    //删除
    handleDelete(index, row) {
      this.$confirm('是否确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delUser(row.id, response=> {
            if(response.status == 204){
              this.getUsersList()
              this.$message.success('删除成功')
            }
          })
        }).catch(() => {
        });
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.searchParam.per_page = val;
      this.getUsersList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.searchParam.page = val;
      this.getUsersList();
    },
    //dialog close
    closeDialog(){
      this.operType = 1;
    },
    //用户状态切换
    statusHandleEdit(index, row){
      this.userId = row.id
      updateUser(this.userId, {
        "status": row.status === 1 ? 0 : 1
      }, response=> {
        const res = response.data;
        if(res.code === 1){
          this.$message.success('操作成功')
          this.getUsersList();
        }
      })
    },
    //添加switch
    add_switchChange(val){
      this.form.status = val ? 1 : 0
    },
    //获取角色
    getRolesList(){
      getRoles(response=> {
      const res = response.data
      if(res.code == 1){
        this.rolesArr = res.data;
      }
    })
    }
  },
  filters:{
    statusFilter(val){
      let text = '';
      if(val == '0'){
        text = '禁用'
      }else if(val == '1'){
        text = '启用'
      }
      return text;
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .mainBox{
    padding: 0px;
    margin-bottom: 20px;
  }
  .container {
    margin: 10px 0px;
  }
</style>
